package com.cr.admin.es;

import org.apache.http.HttpHost;
import org.aspectj.lang.annotation.Before;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.Test;

import java.io.IOException;

public class ESDocTestRun {
    private RestHighLevelClient client;

    public ESDocTestRun() {
        initClient(); // 在构造函数中初始化客户端
    }

    public void initClient() {
        HttpHost host = new HttpHost("localhost", 9200, "http");
        RestClientBuilder builder = RestClient.builder(host);
        client = new RestHighLevelClient(builder);
    }

    public void closeClient() throws IOException {
        if (client != null) {
            client.close();
        }
    }

    @Test
    public void createMappingIndex() throws IOException {
        CreateIndexRequest request = new CreateIndexRequest("news");
        Settings.Builder setting =
                Settings.builder()
                        .put("number_of_shards", 1)
                        .put("number_of_replicas", 0);
        request.settings(setting);
        String mapping = "{\"properties\":{\"title\":{\"type\":\"text\",\"analyzer\":\"ik_max_word\"},\"brief\":{\"type\":\"text\",\"analyzer\":\"ik_max_word\"},\"content\":{\"type\":\"text\",\"analyzer\":\"ik_max_word\"}}}";
        request.mapping(mapping, XContentType.JSON);
        client.indices().create(request, RequestOptions.DEFAULT);
    }


}
